<template>
  <div class="page">
    <section class="card card-header">
      <div class="device-name">
        <button class="icon-btn" aria-label="back" @click="$router.back()">
          ◀
        </button>
        {{ deviceName }}</div>
      <button
        class="chip chip-power"
        :class="{ on: state.powerOn }"
        @click="onTogglePower"
      >
        {{ state.powerOn ? "关机" : "开机" }}
      </button>
    </section>

    <section class="card mode-block">
      <div class="section-title">模式</div>
      <div class="mode-chips">
        <button
          class="chip"
          :class="{ active: mode.value === 3 }"
          @click="onChangeMode(3)"
        >
          制热
        </button>
        <button
          class="chip"
          :class="{ active: mode.value === 4 }"
          @click="onChangeMode(4)"
        >
          通风
        </button>
        <button
          class="chip"
          :class="{ active: mode.value === 5 }"
          @click="onChangeMode(5)"
        >
          制冷
        </button>
      </div>
    </section>

    <section class="card temp-block" v-if="mode.value !== 4">
      <div class="section-title">温度</div>
      <div class="temp-content">
        <TempDial
          :current-temp="displayTemp"
          :min-temp="limits.min"
          :max-temp="limits.max"
          :disabled="!state.powerOn"
        />
        <div class="temp-side">
          <div class="temp-ctrl">
            <button
              class="btn-round"
              :disabled="!state.powerOn"
              @click="onChangeTemp(-1)"
            >
              −
            </button>
            <div class="temp-display">{{ displayTemp.toFixed(1) }}℃</div>
            <button
              class="btn-round"
              :disabled="!state.powerOn"
              @click="onChangeTemp(1)"
            >
              +
            </button>
          </div>
          <div class="hint" v-if="!state.powerOn">已关机，无法调节</div>
        </div>
      </div>
    </section>

    <section class="card speed-block">
      <div class="section-title">风速</div>
      <div class="speed-chips">
        <button
          v-for="s in speeds"
          :key="s.label"
          :disabled="!state.powerOn && s.value !== 0"
          :class="['chip', { active: wind.value === s.value }]"
          @click="onChangeWind(s.value)"
        >
          {{ s.label }}
        </button>
      </div>
    </section>
  </div>
</template>

<script setup>
import { reactive, computed } from "vue";
import { useRoute } from "vue-router";
import TempDial from "../components/TempDial.vue";
import { setDeviceStatus } from "../services/api.js";

const route = useRoute();
let saved = null;
try {
  saved = JSON.parse(sessionStorage.getItem("deviceInfo") || "null");
} catch {}
const deviceFromState = saved || history.state?.device || null;

const device = reactive({
  deviceName: route.query.device || deviceFromState?.deviceName || "--",
  mac: route.query.mac || deviceFromState?.mac || "",
  pattern: deviceFromState?.pattern || "",
  windSpeed: deviceFromState?.windSpeed || "",
  heatingTemperature: deviceFromState?.heatingTemperature || null,
  cryogenicTemperature: deviceFromState?.cryogenicTemperature || null,
  min: typeof deviceFromState?.min === "number" ? deviceFromState.min : 16,
  max: typeof deviceFromState?.max === "number" ? deviceFromState.max : 30,
});

const deviceName = computed(() => device.deviceName);

const limits = reactive({
  min: device.min,
  max: device.max,
});

// 根据模式确定初始温度
function getInitialTemp() {
  const pattern = device.pattern.toLowerCase();
  console.log(
    "Pattern:",
    pattern,
    "Heating:",
    device.heatingTemperature,
    "Cryogenic:",
    device.cryogenicTemperature
  );
  if (pattern === "heating" && device.heatingTemperature !== null) {
    return device.heatingTemperature;
  } else if (pattern === "cooling" && device.cryogenicTemperature !== null) {
    return device.cryogenicTemperature;
  }
  return 25; // 默认温度
}

const initialTemp = getInitialTemp();
const initialPower = deviceFromState?.deviceStatus === "operation";

const state = reactive({
  powerOn: initialPower,
  currentTemp: initialTemp,
});

const speeds = [
  { label: "低", value: 0 },
  { label: "中", value: 1 },
  { label: "高", value: 2 },
  { label: "自动", value: 3 },
];

const wind = reactive({ value: mapWindTextToValue(device.windSpeed) });
const uiWindSpeed = computed(() => mapWindValueToText(wind.value));

// 根据pattern初始化模式
const mode = reactive({ value: mapPatternToMode(device.pattern) });

// 计算当前显示的温度
const displayTemp = computed(() => {
  // 优先显示用户调节的温度
  if (mode.value === 3) {
    // 制热
    return state.currentTemp;
  } else if (mode.value === 5) {
    // 制冷
    return state.currentTemp;
  }
  return state.currentTemp;
});

function mapPatternToMode(pattern) {
  switch (String(pattern).toLowerCase()) {
    case "heating":
    case "制热":
      return 3;
    case "ventilation":
    case "通风":
    case "fan":
    case "blowing_in":
      return 4;
    case "cooling":
    case "制冷":
      return 5;
  }
}

function mapWindTextToValue(text) {
  switch (String(text).toLowerCase()) {
    case "low":
    case "低":
      return 0;
    case "center":
    case "middle":
    case "中":
      return 1;
    case "high":
    case "高":
      return 2;
    case "auto":
    case "自动":
      return 3;
    default:
      return 1;
  }
}

function mapWindValueToText(v) {
  return v === 0 ? "低" : v === 1 ? "中" : v === 2 ? "高" : "自动";
}

async function onTogglePower() {
  state.powerOn = !state.powerOn;
  if (!device.mac) return;
  const command = state.powerOn ? 1 : 2;
  try {
    await setDeviceStatus({ mac: device.mac, command, temperature: undefined });
  } catch (e) {
    console.warn("set power fail", e);
  }
}

async function onChangeMode(next) {
  if (!state.powerOn) return;
  mode.value = next;
  if (!device.mac) return;
  const temperature = next === 4 ? undefined : state.currentTemp;
  try {
    await setDeviceStatus({ mac: device.mac, command: next, temperature });
  } catch (e) {
    console.warn("set mode fail", e);
  }
}

async function onChangeWind(next) {
  if (!state.powerOn) return;
  wind.value = next;
  if (!device.mac) return;
  try {
    await setDeviceStatus({ mac: device.mac, command: 6, temperature: next });
  } catch (e) {
    console.warn("set wind fail", e);
  }
}

async function onChangeTemp(delta) {
  if (!state.powerOn) return;
  const next = Math.max(
    limits.min,
    Math.min(limits.max, state.currentTemp + delta)
  );
  if (Math.abs(next - state.currentTemp) < 0.1) return; // 避免微小变化
  state.currentTemp = next;
  if (!device.mac) return;
  try {
    await setDeviceStatus({ mac: device.mac, command: 5, temperature: next });
  } catch (e) {
    console.warn("set temp fail", e);
  }
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: var(--bg);
  color: var(--text);
}
.topbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.04);
}
.icon-btn {
  border: none;
  background: transparent;
  font-size: 20px;
  line-height: 1;
}
.title {
  font-weight: 600;
  font-size: 16px;
}
.right-actions {
  display: flex;
  gap: 8px;
}
.card {
  background: #fff;
  margin: 12px 12px 0;
  border-radius: 12px;
  box-shadow: 0 10px 24px rgba(31, 85, 255, 0.06);
}
.card-header {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.device-name {
  font-weight: 600;
  color: #1f55ff;
}
.section-title {
  padding: 16px 16px 0;
  color: #666;
  font-size: 14px;
}
.info {
  padding: 12px 16px;
}
.info .row {
  display: flex;
  justify-content: space-between;
  padding: 6px 0;
  color: #333;
}
.mode-block {
  padding: 12px 12px 16px;
}
.mode-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px 4px 0 12px;
}
.temp-block {
  padding: 12px 12px 16px;
}
.temp-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  align-items: center;
  gap: 8px;
  padding: 8px 12px 16px;
}
.temp-side {
  display: grid;
  gap: 12px;
  justify-items: center;
}
.temp-ctrl {
  display: grid;
  grid-template-columns: auto auto auto;
  align-items: center;
  gap: 12px;
}
.btn-round {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: none;
  background: #f2f6ff;
  color: #4a69ff;
  font-size: 22px;
  box-shadow: 0 8px 20px rgba(31, 85, 255, 0.14);
}
.btn-round:disabled {
  opacity: 0.5;
}
.temp-display {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}
.hint {
  font-size: 12px;
  color: #999;
}
.speed-block {
  padding: 12px 12px 16px;
}
.speed-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px 4px 0 12px;
}
.chip {
  background: #f2f6ff;
  color: #4a69ff;
  border: none;
  border-radius: 8px;
  padding: 8px 10px;
  font-size: 12px;
  box-shadow: 0 8px 20px rgba(31, 85, 255, 0.14);
}
.chip.active {
  background: #1f55ff;
  color: #fff;
}
.chip:disabled {
  opacity: 0.5;
}
.chip-power.on {
  background: #ff4d4f;
  color: #fff;
}
</style>
